﻿using Asion.Dapper.SqlBuilder;
using Dapper;
using System;
using System.Collections.Generic;
using System.Data;
using System.Text;
using static Asion.Dapper.SqlMapperExtensions;

namespace Asion.Dapper
{
    public abstract class BaseCondition : IGetSql, IPrintSql
    {

        public BaseCondition()
        {

        }

        public void Build(Type type)
        {
            var info = SqlMapperExtensions.GetPropertiesCache(new PropertyIdentity(type));
            _custom_table_mappinghandle = new SimpleCustomTableMappingHandle(info);


            var name = TenantMananger.GetTenantsName(type);
            var dbtype = DapperConfiguration.connection_factory.GetDbType(name);

            _encap_sulation = EncapSulationFactory.Create(dbtype);
        }


        internal IEncapSulation _encap_sulation;

        internal ICustomTableMappingHandle _custom_table_mappinghandle;


        internal DynamicParameters DynamicParam { get; set; }


        internal bool IsGetSql = false;


        internal string Sql = "";


        internal void AddDynamicParam(string name, object value)
        {
            if (DynamicParam == null)
            {
                DynamicParam = new DynamicParameters();
            }
            DynamicParam.Add(name, value);
        }


        internal void AddDynamicParam(string name, object value, System.Data.DbType dbtype, CondtionOperator oprator)
        {
            if (DynamicParam == null)
            {
                DynamicParam = new DynamicParameters();
            }
            if (oprator == CondtionOperator.In)
            {
                DynamicParam.Add(name, value);
            }
            else
            {
                DynamicParam.Add(name, value, dbtype);
            }

        }

        internal void AddDynamicParam(DynamicParameters dynamic)
        {

            if (DynamicParam == null)
            {
                DynamicParam = new DynamicParameters();
            }
            DynamicParam.AddDynamicParams(dynamic);

        }

        internal void ClearDynamicParam()
        {
            if (DynamicParam != null)
            {
                DynamicParam = new DynamicParameters();
            }
        }

        public string GetSql()
        {
            if (IsGetSql)
            {
                return Sql;
            }
            Sql = BuildSql();
            IsGetSql = true;
            return Sql;


        }

        public abstract string BuildSql();

        public string PrintSql()
        {
            return GetSql();
        }
    }
}
